import roleApi from '@/api/roleApi'
import type { IAction, IModalProps } from '@/types/modal'
import type { RoleItem } from '@/types/roleType'
import { message } from '@/utils/AntdGlobal'
import { Form, Input, Modal } from 'antd'
import { useImperativeHandle, useState } from 'react'

const CreateRole = (props: IModalProps<RoleItem>) => {
  const [aciton, setAction] = useState<IAction>('create')
  const [visible, setVisible] = useState(false)
  const [form] = Form.useForm()
  useImperativeHandle(props.mRef, () => {
    return {
      open
    }
  })
  const open = (type: IAction, data?: RoleItem) => {
    setAction(type)
    setVisible(true)
    if (type === 'edit' && data) {
      form.setFieldsValue(data)
    }
  }
  const handleCancel = () => {
    setVisible(false)
    form.resetFields()
  }
  const handleSubmit = async () => {
    await form.validateFields()
    const params = form.getFieldsValue(true)
    if (aciton === 'create') {
      await roleApi.createRole(params)
      message.success('创建成功')
    }
    if (aciton === 'edit') {
      await roleApi.editRole(params)
      message.info('编辑成功')
    }
    props.update()
    handleCancel()
  }
  return (
    <Modal
      onCancel={handleCancel}
      onOk={handleSubmit}
      open={visible}
      title={aciton === 'create' ? '新增角色' : '编辑角色'}
      width={800}
      okText='确定'
      cancelText='取消'
    >
      <Form form={form} labelCol={{ span: 4 }}>
        <Form.Item label='角色名称' name='roleName' rules={[{ required: true, message: '请输入角色名称' }]}>
          <Input placeholder='请输入角色名称'></Input>
        </Form.Item>
        <Form.Item label='备注' name='remark'>
          <Input.TextArea placeholder='请输入备注'></Input.TextArea>
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default CreateRole
